<!--
 * @Author: taosong
 * @Date: 2023-02-17 13:18:21
 * @LastEditors: taosong
 * @LastEditTime: 2023-02-24 14:29:31
 * @Description: taosongs
-->
<template>
	<div class="overflow-auto flex flex-col items-center">
		<m-svg-icon v-if="isMobileTerminal" name="close" class="w-3 h-3 p-0.5 m-1 ml-auto"
			fillClass="fill-zinc-900 dark:fill-zinc-200 " @click="close"></m-svg-icon>

		<img ref="imageTarget" :src="blob" />

		<m-button :loading="loading" class="mt-4 w-[80%] xl:w-1/2" @click="onConfirmClick">确定</m-button>
	</div>
</template>

<script>
const EMIT_CLOSE = 'close'
// 移动端配置对象
const mobileOptions = {
	// 将裁剪框限制在画布的大小
	viewMode: 1,
	// 移动画布，裁剪框不动
	dragMode: 'move',
	// 裁剪框固定纵横比：1:1
	aspectRatio: 1,
	// 裁剪框不可移动
	cropBoxMovable: false,
	// 不可调整裁剪框大小
	cropBoxResizable: false
}

// PC 端配置对象
const pcOptions = {
	// 裁剪框固定纵横比：1:1
	aspectRatio: 1
}
</script>

<script setup>
import Cropper from 'cropperjs'
import { getOSSClient } from '@/utils/sts'
import { message } from '@/libs'
import { onMounted, ref } from 'vue'
import 'cropperjs/dist/cropper.css'
import { isMobileTerminal } from '@/utils/flexible'
import { putProfile } from '@/api/system'
import { useStore } from 'vuex'
defineProps({
	blob: {
		type: String,
		required: true
	}
})
const emits = defineEmits([EMIT_CLOSE])

// 定义图片节点
const imageTarget = ref(null)
let cropper
onMounted(() => {
	cropper = new Cropper(
		// 两个参数第一个参数 图片的dom 第二个参数是配置的裁剪对象
		imageTarget.value,
		isMobileTerminal.value ? mobileOptions : pcOptions
	)
})
// 按钮的loading
const loading = ref(false)
// 确定按钮点击事件
const onConfirmClick = () => {
	// 开启 loading
	loading.value = true
	// 获取裁剪后的图片
	cropper.getCroppedCanvas().toBlob((blob) => {
		// 创建cos实例
		// const imgSrc = URL.createObjectURL(blob)
		putObjectToOSS(blob)
	})
}

/**
 * 更新用户头像
 *
 */
const onChangeAvatar = async (avatar) => {
	// 修改本地
	store.commit('user/setUserInfo', {
		...store.getters.userInfo,
		avatar
	})
	// 修改服务器
	await putProfile(store.getters.userInfo)
	loading.value = false
	message('success', '用户头像修改成功')
	close()
}

/**
 * 进行 OSS 上传
 */
let ossClient = null
let store = useStore()
const putObjectToOSS = async (file) => {
	if (!ossClient) {
		ossClient = await getOSSClient()
	}
	try {
		// 因为当前凭证只具备 images 文件夹下的访问权限，所以图片需要上传到 images/xxx.xx 。否则你将得到一个 《AccessDeniedError: You have no right to access this object because of bucket acl.》 的错误
		const fileTypeArr = file.type.split('/')
		const fileName = `${store.getters.userInfo.username}/${Date.now()}.${fileTypeArr[fileTypeArr.length - 1]
			}`
		// 文件存放路径，文件
		const res = await ossClient.put(`images/${fileName}`, file)
		// TODO：图片上传成功
		// console.log(res.url, '成功')
		onChangeAvatar(res.url)
	} catch (e) {
		message('error', e)
	}
}

// 移动端下关闭
const close = () => {
	emits(EMIT_CLOSE)
}
</script>
<style lang="scss" scoped></style>
